package com.lpgu.scan;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Set;


/**
 * @author: lpgu
 * @describe:JpaClassBeanDefinitionScanner
 * @createAt: 2022/1/5 21:25
 * 自定义扫描器
 * 原有的不变，自己通过动态注册去扫描
 */
public class JpaClassBeanDefinitionScanner extends ClassPathBeanDefinitionScanner {
    public JpaClassBeanDefinitionScanner(BeanDefinitionRegistry registry) {
        super(registry);
    }

//如果是接口就当成有效组件，必须实现了Repository接口

    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        AnnotationMetadata metadata = beanDefinition.getMetadata();
        return metadata.isInterface();
    }

    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
            ScannedGenericBeanDefinition beanDefinition =(ScannedGenericBeanDefinition) beanDefinitionHolder.getBeanDefinition();
            String beanClassName = beanDefinition.getBeanClassName();
            //设置构造函数
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);
            //偷天换日
            beanDefinition.setBeanClass(JpaFactoryBean.class);

        }
        return beanDefinitionHolders;
    }
}
